package com.house.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.house.common.R;
import com.house.dto.UserDto;
import com.house.entity.User;
import com.house.service.UserService;
import com.house.util.Md5Util;
import com.house.util.RedisUtil;
import com.house.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${spring.cache.redis.time-to-live}")
    private Integer timeout;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 用户登录
     * @param requestUserFrom
     * @return
     */
    @PostMapping("/login")
    public R<UserDto>  login(@RequestBody User requestUserFrom){
        User user = userService.selectUserByUserName(requestUserFrom.getUserName());
        if (user == null) {
            return R.error("用户不存在！");
        }
        String password = requestUserFrom.getPassword();
        password = Md5Util.md5(password);
        if (!user.getPassword().equals(password)) {
            return R.error("密码错误！");
        }
        if (user.getRoleId() == 0) {
            return R.error("用户未分配角色");
        }
        if (user.getStatus() != 1) {
            return R.error("账号已被禁用，请联系管理员");
        }
        user.setPassword("");
        UserDto userDto = new UserDto();
        userDto.setUser(user);
        String token = TokenUtils.token(user.getUserName(), user.getPassword());
        userDto.setToken(token);
        String userId = String.valueOf(user.getId());
        redisUtil.setCacheObject(userId, user, timeout, TimeUnit.SECONDS);
        redisUtil.setCacheObject(token, userId, timeout, TimeUnit.SECONDS);
        return R.success(userDto);
    }

    @PostMapping("/loginOut")
    public R<String> loginOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        if ("".equals(token)) {
            return R.error("您尚未登录！");
        }
        redisUtil.deleteObject(token);
        return R.success("退出登录！");
    }

    /**
     * 获取用户分页
     * @param page
     * @param pageSize
     * @param userName
     * @return
     */
    @GetMapping ("/getUsers")
    public R<Page<User>> getUsers(int page, int pageSize, String userName) {
        Page<User> pageInfo = userService.selectPage(page, pageSize, userName);
        return R.success(pageInfo);
    }

    /**
     * 保存用户
     * @param user
     * @return
     */
    @PostMapping("/save")
    public R<String> save(@RequestBody User user) {
        userService.save(user);
        return R.success("添加成功!");
    }

    /**
     * 根据id获取用户
     * @param id
     * @return
     */

    @GetMapping("/getUserById/{id}")
    public R<User> getUserById(@PathVariable Long id) {
        User user = userService.selectUserById(id);
        return R.success(user);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */

    @PutMapping("/update")
    public R<String> update(@RequestBody User user) {
        userService.update(user);
        return R.success("更新成功!");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */

    @DeleteMapping("/delete/{id}")
    public R<String> delete(@PathVariable Long id) {
        int res = userService.delete(id);
        if (res == 0) {
            return R.error("删除失败!");
        }
        return R.success("删除成功!");
    }
}

